<template>
  <div class="ma-content-block  p-4">
    <!-- CRUD 组件 -->
    <ma-crud :options="options" :columns="columns" ref="crudRef">
      <template #pay_real_price="{ record }">
            <a-popover :title="`费用明细（合计金额：${(record.pay_real_price - 0).toFixed(2)}）`" position="right">
              <a-link v-if='record?.pay_status == 1 || record?.pay_status == 2' status="success">+ {{(record?.pay_real_price - 0).toFixed(2) - 0}} </a-link>
              <a-link v-if='record?.pay_status == 3 || record?.pay_status == 4' status="danger">- {{(record?.pay_real_price - 0).toFixed(2) - 0}} </a-link>
              <template #content>
                <div style='min-width:300px'>
                  <a-table :columns="tablecolumnsts" :data="record.detail" :pagination='false' :span-method="spanMethodAll" :bordered="{wrapper: true, cell: true}" />
                </div>
              </template>
            </a-popover>
      </template>
      <template #pay_status="{ record }">
        <div v-if="record.is_confirm == 1">{{record?.pay_status == 1?'已支付':record?.pay_status == 2?'未支付':record?.pay_status == 3 && record?.pay_type == 'periodic'?'已退款':record?.pay_status == 3 && (record?.pay_type == 'now_pay' || record?.pay_type == 'money')?'已退款（退款到余额）':record?.pay_status == 4?'已取消':''}}</div>
        <div v-if="record.is_confirm == 0">待确认</div>
      </template>
      <template #summaryCell="{ column, record }">
          {{
              column.dataIndex == "order_number" ? "小计" : column.dataIndex == "pay_price" ? (record[column.dataIndex] - 0).toFixed(2) : record[column.dataIndex]
          }}
      </template>
    </ma-crud>
    <div class='lg:flex'>
      <div>合计：{{(heji - 0).toFixed(2)}}</div>
    </div>
  </div>
</template>
<script setup>
import { ref, reactive } from 'vue'
import { request } from "@/utils/request.js";
import financialPayOrder from '@/api/financial/financialPayOrder'
import { Message } from '@arco-design/web-vue'
import tool from '@/utils/tool'
import * as common from '@/utils/common'

const crudRef = ref()
const xiaoji = ref()
const heji = ref(0)
const indexid = ref(0)
const open =  (row) => {
  indexid.value = row.user_id
  crudRef.value.refresh()
}
const tablecolumnsts = [
      {
        title: '车号',
        dataIndex: 'car_nos',
      },
      {
        title: '收费项目',
        dataIndex: 'pay_name',

      },
      
      {
        title: '原金额',
        dataIndex: 'pay_price',
      },
      {
        title: '实际金额',
        dataIndex: 'pay_real_price',
      },
      {
          title: '优惠金额',
          dataIndex: 'discount_price',
      },
      {
        title: '天-D',
        dataIndex: 'day',
      },
      {
        title: '吨-T',
        dataIndex: 'weight',
      },
      {
        title: '车-C',
        dataIndex: 'car_no_value',
      },
      {
        title: '箱-X',
        dataIndex: 'box',
      },
      {
        title: '计费规则',
        dataIndex: 'chi_price_role',
      },
      {
        title: '备注',
        dataIndex: 'remark',
      },
];
const  spanMethodAll= ({record,rowIndex, columnIndex}) => {
    if (rowIndex === record.weizhi - record.weizhizong && columnIndex === 0) {
      return {rowspan: record.weizhizong,colspan:1}
    }

   
};
const handleSOrt = (ceshiArr)=>{
  let arr = []           // 最终数据
  let linshiArr = []     //  未匹配的放数组里
  let linshititle = ''   // 临时变量
  ceshiArr.map((v,i)=>{
    if(i == 0){
      linshititle = v.name
      arr.push(v)
    }else{
      if(linshititle == v.name){
        arr.push(v)
      }else{
        linshiArr.push(v)
      }
    }
  })
  ceshiArr.map((v,i)=>{
    if(linshiArr.length != 0){
      linshiArr.map((vv,ii)=>{
        if(ii == 0){
          linshititle = linshiArr[0].name
          arr.push(linshiArr.shift())
        }else{
          if(linshititle == vv.name){
            arr.push(linshiArr.slice(ii,1))
          }
        }
        
      })
      
    }
  })
  arr.sort((a, b) => a.car_nos.localeCompare(b.car_nos));
  return arr
}
const options = reactive({
  id: 'flyos_financial_pay_order',
  rowSelection: {
    showCheckedAll: true
  },
  pk: 'id',
  // autoRequest: false,
  showSummary: true,
  summary: [
        // 定义 amountA 字段加总合计
        {
            dataIndex: 'pay_price',
            action: 'sum'
        },
    ],
  operationColumn: false,
  operationWidth: 160,
  
  formOption: {
    viewType: 'modal',
    width: 600
  },
  api: financialPayOrder.getList,
  add: {
    show: false,
    api: financialPayOrder.save,
    auth: ['financial:payOrder:save']
  },
  edit: {
    show: false,
    api: financialPayOrder.update,
    auth: ['financial:payOrder:update']
  },
  delete: {
    show: false,
    api: financialPayOrder.deletes,
    auth: ['financial:payOrder:delete']
  },
  export: {
    show: true,
    url: 'financial/payOrder/export',
    auth: ['financial:payOrder:export']
  },
  beforeRequest: (params) => {
    console.log(params)
    params.dept_id = indexid.value
    if(params?.pay_date && params?.pay_date.length != 0){
      params.pay_date[0] = params.pay_date[0] + ' 00:00:00'
      params.pay_date[1] = params.pay_date[1] + ' 23:59:59'
    }
    // params.pay_date = 'periodic';
    // params.pay_status = '1';
   
    request({
      url:'financial/payOrder/total',
      method: 'get',
      params,
    }).then(res=>{
      heji.value = res.data.total
    })
  },
  afterRequest: (params) => {
    let number = 0
		params.map((v, i) => {
			let arr = []
      let arrs = []
      if(v.pay_status != 3){
        v.detail.map((vv,ii)=>{
          // if(v.prediction_id){  //  到站收费
          if(!vv.prediction){
            vv.prediction = v.send
          }
            vv.car_nos = vv.prediction.car_no
            vv.no_tax_price = (vv.no_tax_price - 0 ).toFixed(2)
            vv.tax_price = (vv.tax_price - 0 ).toFixed(2)
            vv.pay_real_price = (vv.pay_real_price - 0 ).toFixed(2)
            vv.pay_price = (vv.pay_price - 0 ).toFixed(2)
            vv.discount_price = (vv.discount_price - 0 ).toFixed(2)
          // }else{
          //   if(v.prediction_order_id != 0 && v.prediction_driver_order_id == 0){  //  补费
          //     vv.car_nos = ''
          //   }else{  // 装车收费
          //     if(vv.order_detail.prediction_id == 0){
          //       vv.car_nos = vv.order_detail.wareuserdetail.car_no
          //     }else{
          //       vv.car_nos = vv.order_detail.prediction.car_no
          //     }
          //   }
            
          // }
          if(vv.pay_price != '0.00' && vv.is_confirm == 1){
            arr.push(vv)
          }
        })
        
        v.detail = handleSOrt(arr)
        let carArr = []
        v.detail.map((vv,ii)=>{
          carArr.push(vv.car_nos)
        })
        var newArr = carArr.filter(function(item,index){
          return carArr.indexOf(item) === index;  // 因为indexOf 只能查找到第一个  
        });
        let numArr = []
        newArr.map((vv,ii)=>{
          let num = 0
          let name = ''
          carArr.map((vvv,iii)=>{
            if(vv == vvv){
              num++
              name = vvv
            }
          })
          numArr.push({car_no:name,weizhi:num,weizhizong:num})
        })
        let weizhiArr = []
        let weizhinum = 0
        numArr.map((vv,ii)=>{
          weizhinum += vv.weizhi
          weizhiArr.push({car_no:vv.car_no,weizhi:weizhinum,weizhizong:vv.weizhizong})
        })
        v.detail.map((vv,ii)=>{
          weizhiArr.map((vvv,iii)=>{
            if(vv.car_nos == vvv.car_no){
              vv.weizhi = vvv.weizhi
              vv.weizhizong = vvv.weizhizong
            }
          })
        })
        v.detail.map((vv,ii)=>{
          vv.pay_price = vv.pay_price - 0
        })
      }
      
      number += (v.pay_price - 0)
		});
    
    xiaoji.value = number
	},
})

const columns = reactive([
// {title: '序号',width: 80,customRender: (record, column, rowIndex) => record.rowIndex + 1,},
  {
    title: "",
    dataIndex: "id",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
    hide: true,
    commonRules: {
      required: true,
      message: "请输入"
    },
    search: false
  },
  {
    title: "交易单号",
    dataIndex: "order_number",
    formType: "input",
    search: true,
    search: false
  },
  {
    title: "关联订单",
    dataIndex: "prediction_order_number",
    formType: "input",
    search: true,
    search: false
  },
  {
    title: "客户名称",
    dataIndex: "dept_id",
    common: true,
    search: false
  },
  {
    title: "交易金额",
    dataIndex: "pay_real_price",
  },
  {
    title: "支付项目",
    dataIndex: "pay_items_json",
    formType: "input",
    hide: true
  },
  {
    title: "历史支付项目",
    dataIndex: "history_pay_items_json",
    formType: "input",
    hide: true
  },
  {
    title: "支付方式",
    dataIndex: "pay_type",
    formType: "select",
    search: false,
    dict: {
      data: [
        {
          label: "现结",
          value: "now_pay"
        },
        {
          label: "周期结算",
          value: "periodic"
        },
        {
          label: "预付款",
          value: "money"
        }
      ],
      translation: true
    }
  },
  {
    title: "支付类型",
    dataIndex: "now_pay_type",
    formType: "select",
    // search: true,
    dict: {
      data: [
        {
          label: "惠支付",
          value: "1"
        },
        {
          label: "现金",
          value: "2"
        },
        {
          label: "对公转账",
          value: "3"
        }
      ],
      translation: true
    }
  },
  {
    title: "支付状态",
    dataIndex: "pay_status",
    formType: "select",
    search: true,
    dict: {
      data: [
        {
          label: "已支付",
          value: "1"
        },
        {
          label: "未支付",
          value: "2"
        },
        {
          label: "已退款",
          value: "3",
        },
        {
          label: "已取消",
          value: "4",
        }
      ],
      translation: true
    }
  },
  // {
  //   title: "支付日期",
  //   dataIndex: "pay_date",
  //   formType: "date",
  //   search: true,
  //   showTime: true
  // },
  {
    title: "支付日期",
    dataIndex: "pay_date",
    formType: "range",
    align: "center",
    search: true,
    addDisplay: false,
    editDisplay: false,
    sortable: {
      sortDirections: ["ascend", "descend"],
      sorter: true,
    },
    showTime: false,
  },
  {
    title: "创建时间",
    dataIndex: "created_at",
    formType: "date",
    addDisplay: false,
    editDisplay: false,
    showTime: true
  },
  {
    title: "备注",
    dataIndex: "remark",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
    hide: true
  },
  // {
  //   title: "转账凭证",
  //   dataIndex: "transfer_voucher_images",
  //   formType: "upload",
  //   type: "image",
  //   multiple: true
  // },
  // {
  //   title: "凭证审核日期",
  //   dataIndex: "check_date",
  //   formType: "date",
  //   search: true,
  //   showTime: true
  // },
  {
    title: "修改时间",
    dataIndex: "updated_at",
    formType: "date",
    addDisplay: false,
    editDisplay: false,
    hide: true,
    showTime: true
  },
  {
    title: "删除时间",
    dataIndex: "deleted_at",
    formType: "date",
    addDisplay: false,
    editDisplay: false,
    hide: true,
    showTime: true
  },
  {
    title: "创建者",
    dataIndex: "created_by",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
    hide: true
  },
  {
    title: "更新者",
    dataIndex: "updated_by",
    formType: "input",
    addDisplay: false,
    editDisplay: false,
    hide: true
  }
])

defineExpose({
  crudRef,
  open
})
</script>
<script> export default { name: 'financial:payOrder' } </script>
